$(function() {
	var page = refreshIpData('',1);
	createTable(page.IPList);
	initPage(page);
});


function quicSsearchCallback(){
	var  ipdata =refreshIpData($('#ip_search').val().replace(/(^\s*)|(\s*$)/g, ""),1);
	createTable(ipdata.IPList);
	initPage(ipdata);
};

var initPage =function(page){
	var totalCount = Number(page.totalCount)|| 1;
	var showPage = 10;
	var showCount = 20;
	var currentPage = Number(page.currentPage) || 1;
	$('#callBackPager').empty();
	$('#callBackPager').extendPagination({
		totalCount : totalCount,
		showPage : showPage,
		showCount : showCount,
		currentPage : currentPage,
		callback : function(curr, showCount, totalCount) {
			var page = refreshIpData($('#ip_search').val().replace(/(^\s*)|(\s*$)/g, ""),curr);
			createTable(page.IPList);
		}
	});
};

/**
 * 刷新Ip列表
 * @param ip_search 搜索
 * @param currentPage 当前页面
 * 
 */
var refreshIpData = function(ip_search,currentPage){
	//初始化页面table数据
	var data1 = {};
	var ip_search = $('#ip_search').val();
	data1.ip_search =ip_search;
	data1.currentPage = currentPage;
	var returnData = ajaxWithServer(null, data1, 'getIpData');
	var dataList = returnData.IPList;
	if (undefined == dataList) {
		dataList = [];
	}
	return returnData;
};
var uploadFile = function() {
	$('#fileid').click();
};


/**
 * 新增或修改的操作
 * 
 * @param option
 *            新增或修改
 * 
 */
var addOrUpdate = function(option) {
	var user = $('#user').val();
	var defaultBatch = "";
	var ip = "";
	var mask = "";
	var mac = "";
	var isIns = false;
	if (option == "add") {
		defaultBatch = getCurrentDate(user);
		$("#optionType").val("add");
		$("#note_div").hide();
	} else {
		// update
		$("#optionType").val("update");
		var allCheck = getSeletcRows()[0];
		$('#trIndex').val($(allCheck).index());
		$('#updateId').val($(allCheck).find("td input[type='checkbox']").val());

		var ipStatus = $(allCheck).find("td").eq(6).text();
		isIns = (ipStatus == "未装机" || ipStatus == "No instlled") ? false : true;
		ip = $(allCheck).find("td span").text();
		mask = $(allCheck).find("td").eq(1).text();
		mac = $(allCheck).find("td").eq(2).text();
		defaultBatch = $(allCheck).find("td").eq(3).text();
		note = $(allCheck).find("td").eq(4).text();
		$("#note_div").show();
	}
	if (isIns) {
//		已经在使用中，不允许修改
		swal('Message',getSpringMsg('ipHasInsMsg',null));
	}else{
		// var ipIn = $("#bantch_inp");
		// ipIn.val(defaultBatch);
		$("#bantch_inp").val(defaultBatch);
		var ips = ['','','',''];
		if(ip !=''){
			ips = ip.split('.');
		}
		$("#ip_1").val(ips[0]);
		$("#ip_2").val(ips[1]);
		$("#ip_3").val(ips[2]);
		$("#ip_4").val(ips[3]);
		
		var masks = ['','','',''];
		if(mask !=''){
			masks = mask.split('.');
		}
		$("#mask_1").val(masks[0]);
		$("#mask_2").val(masks[1]);
		$("#mask_3").val(masks[2]);
		$("#mask_4").val(masks[3]);

		$("#mac_inp").val(mac);
		$("#note_inp").val("");
		
		$('#os3_ipfp').css('display', 'inline');
		clearAllError();
	}
	
};

var closePop = function(data) {
	$('#os3_ipfp').css('display', 'none');
	$('#os3_ipfp .popdiv-mask .popdiv .popdiv_cnt ul .pop_error').remove();
};
/**
 * 获取当前时间/批次
 * 
 * @author
 * @param user
 *            当前用户
 * @return 批次
 */
var getCurrentDate = function(user) {
	var myDate = new Date();
	var yy = myDate.getFullYear();
	var MM = myDate.getMonth() + 1;
	var dd = myDate.getDate();
	var hh = myDate.getHours(); // 获取当前小时数(0-23)
	var mm = myDate.getMinutes(); // 获取当前分钟数(0-59)
	var ss = myDate.getSeconds(); // 获取当前秒数(0-59)
	return yy + "" + MM + "" + dd + "" + "_" + user;
};

/**
 * clear all error message
 * 
 */
var clearAllError = function() {
	$('#batch_error').remove();
	$('#ip_error').remove();
	$('#mask_error').remove();
	$('#mac_error').remove();
	$('#note_error').remove();

};

/**
 * 添加错误显示框,注意，需要在配置文件中配置中英文转换
 * 
 * @param op
 *            错误信息的头
 * @param message
 *            错误信息体
 */
var appendErrorMsg = function(id) {
	return '<div id="' + id
			+ '" class="alert alert-danger fade in"><strong></strong></div>';
};

/**
 * 获取当前table选中的所有的行
 * 
 * @author GuoPengFei
 * @date 2016-04-14
 */
var getSeletcRows = function() {
	var trs = $("#ip_table tr");
	// trs = table.children("tr");
	var allChecked = [];
	trs.each(function() {
		try {
			tempChecked = $(this).find("td input[type='checkbox']").is(
					':checked');
		} catch (e) {
			return true;
		}
		// 计数被选择的个数
		if (tempChecked)
			allChecked.push(this);
	});

	return allChecked;
};

/**
 * delete ip
 * 
 * @param data
 *            dom for the delete row
 * @return delete statu
 */
var deleteIps = function() {
	// get the count of the checkbox
	table = $("#ip_table");
	trs = table.find("tr");
	var count = 0;
	var ids = [];
	trs.each(function() {
		try {
			var checkBox = $(this).find("td input[type='checkbox']");
			if (checkBox.is(':checked')) {
				count++;
				ids.push(checkBox.val());
			}
		} catch (e) {
			// ignore th for table
		}
	});
	
	swal({
				title : getSpringMsg('Delete',null),
				text : getSpringMsg('ConfirmDeleteIps',count),
				type: "warning",
				showCancelButton: true,   
				confirmButtonColor: "#DD6B55",   
				confirmButtonText: getSpringMsg("okdelete",null),   
				cancelButtonText: getSpringMsg("cancel",null),   
				closeOnConfirm: false,   
				closeOnCancel: true
			},
			function(isConfirm) {
				if(isConfirm){
					var data = {};
					data.ids = ids.join(",");

					var resultJs = ajaxWithServer(null, data, "deleteIps");
					if (resultJs.result)
						window.location.href = "ipConfig";
					else
						swal("Message", resultJs.message);
				}
		});
};
/**
 * detail for ip
 * 
 * @param data
 *            dom for the select row
 * 
 */
var viewDetail = function(data) {
	swal("Message!", "即将删除");
//	alert("即将删除");
};
/**
 * Data interaction with the background server
 * 
 * @param opType
 *            optioion type
 * @param data
 *            send to background server with json type
 * @param action
 *            request mapping
 */
var ajaxWithServer = function(opType, data, action) {
	var json = {};
	$.ajax({
		type : "POST",
		datatype : "json",
		contentType : "application/json; charset=utf-8",
		url : action,
		async : false,
		data : JSON.stringify(data),
		success : function(dataJson) {
			json = dataJson;
		},
		error : function() {
			json.result = false;
			json.message = "Net error!";
		}
	});
	return json;
};


/**
 * 实现上传功能
 */
var updloadFile = function(id) {
	var temp = $('#' + id).click();
	// alert(JSON.stringify(temp));
};

/**
 * 检查修改或新增的某类数据是否已经存在
 * 
 * @param tableName
 *            table id
 * @param value
 *            colum value
 * @param colum
 *            td index+1
 * @param opType
 *            add or update option
 * 
 */
var checkNameIsExist = function(tableName, value, colum, opType) {
	table = $("#" + tableName);
	trs = table.find("tr");
	var trIndex = $('#trIndex').val();
	var isExist = false;
	trs.each(function() {
		try {
			if (colum == 1) {
				if (opType == "update") {
					if ($(this).index() == trIndex)
						return true;
				}
				var ip = $(this).find("td span").text();
				if (ip == value) {
					isExist = true;
					return false;
				}
			} else {
				if (opType == "update") {
					if ($(this).index() == trIndex)
						return true;
				}
				var temp = $(this).find("td").eq(colum - 1).text();
				if (temp == value) {
					isExist = true;
					return false;
				}
			}

		} catch (e) {
			// TODO: handle exception
		}
	});

	return isExist;
};
